<?php
declare(strict_types = 1);


namespace App\Model\Logic;


use App\Helper\RedisConst;
use App\Model\Entity\SignTimezoneRecord;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * Class TimeZoneLogic
 * @package App\Model\Logic
 */
class TimeZoneLogic
{

    /**
     * @Inject("redis1.pool")
     * @var Pool
     */
    private $redis1;

    /**
     * 获取 用户时区
     * @param $member_id
     * @return mixed
     */
    public function getMemberTimeZoneRedis($member_id)
    {
        $timezone_key = RedisConst::MEMBER_TIMEZONE . $member_id;
        $member_timezone =  $this->redis1->get($timezone_key);

        if(is_numeric($member_timezone))
        {
            return (int) $member_timezone;
        }

        $member_timezone = $this->getMemberTimezoneByMemberId($member_id);
        if($member_timezone == '-24')
        {
            return -24;
        }

        $this->setMemberTimezoneRedis($member_id, $member_timezone);

        return (int) $member_timezone;
    }

    /**
     * 获取用户的时区
     * @param $member_id
     * @param bool $return_timezone
     * @return int
     */
    public function getMemberTimezoneByMemberId($member_id, $return_timezone = true)
    {
        if(!$member_id)
        {
            return 0;
        }

        $member_tinezone = SignTimezoneRecord::where('member_id', (int) $member_id)->first()->toArray();
        if(!$member_tinezone)
        {
            return -24;
        }

        if($return_timezone)
        {
            return $member_tinezone['timezone'];
        }

        return $member_tinezone;
    }

    /**
     * 设置用户时区
     * @param $member_id
     * @param $timezone
     */
    public function setMemberTimezoneRedis($member_id, $timezone)
    {
        $timezone_key = RedisConst::MEMBER_TIMEZONE . $member_id;
        return $this->redis1->set($timezone_key, $timezone);
    }


}